﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using WebApiV2.Data.Entity;
using WebApiV2.Domain;

namespace WebApiV2.Data
{
    public class DbInitializer
    {
        public static void Seed(IServiceProvider serviceProvider)
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var db = scope.ServiceProvider.GetService(typeof(Admin678DbContext)) as Admin678DbContext;

                var _userRespository = scope.ServiceProvider.GetService(typeof(IRespository<Users>)) as EfRespository<Users>;

                var _roleRespository = scope.ServiceProvider.GetService(typeof(IRespository<Roles>)) as EfRespository<Roles>;

                db.Database.EnsureCreated();

                var hasUsers = db.Users.Any();

                if (!hasUsers)
                {
                    var role = new Roles
                    {
                        RolesName = "管理员",
                        Description = "这是一个管理员",
                    };
                    
                    _roleRespository.Insert(role);

                    //db.Roles.Add(role);

                    //db.SaveChanges();

                    _userRespository.InsertBulk(new Users[]
                    {
                        new Users
                        {
                            UsersName="hhm",
                            Password="6668",
                            RolesId=role.Id
                        },
                        new Users
                        {
                            UsersName="zxy",
                            Password="9998",
                            RolesId=role.Id
                        }
                    });

                    //db.SaveChanges();

                }
            }
        }
    }
}
